//
//  UINavigationBar+Extension.swift
//  BaoKeSwift
//
//  Created by geek-duan on 2017/10/13.
//  Copyright © 2017年 geek-duan. All rights reserved.
//

import Foundation
import UIKit


// MARK: - 隐藏导航栏
extension UINavigationBar {
    // MARK: - 接口
    /**
     *  隐藏导航栏下的横线，背景色置空 viewWillAppear调用
     */
    func star() {
        let shadowImg: UIImageView? = self.findNavLineImageViewOn(view: self)
        shadowImg?.isHidden = true
        /// - 如果自定义导航栏添加了barTintColor 则这里设为nil 在reset() 方法中再把颜色设置回来
        self.isTranslucent = true
        self.barTintColor = nil
        let image: UIImage? = UIImage().imageFromColor(color: UIColor.themeColor.withAlphaComponent(0))
        self.setBackgroundImage(image, for: .default)
    }
    
    /**
     在func scrollViewDidScroll(_ scrollView: UIScrollView)调用
     @param color 最终显示颜色
     @param scrollView 当前滑动视图
     @param value 滑动临界值，依据需求设置
     */
    func change(_ color: UIColor, with scrollView: UIScrollView, andValue value: CGFloat = 64) {
        
        let y = scrollView.contentOffset.y
        
        // 计算透明度
        let alpha: CGFloat = y / value > 1.0 ? 1 : y / value
        
        let image: UIImage? = UIImage().imageFromColor(color: color.withAlphaComponent(alpha))
        self.setBackgroundImage(image, for: .default)
    }
    
    /**
     *  还原导航栏  viewWillDisAppear调用
     */
    func reset() {
        self.setBackgroundImage(UIImage().imageFromColor(color: UIColor.themeColor), for: .default)
        self.barTintColor = UIColor.themeColor
        self.isTranslucent = false
    }
    
    // MARK: - 其他内部方法
    //寻找导航栏下的横线  （递归查询导航栏下边那条分割线）
    fileprivate func findNavLineImageViewOn(view: UIView) -> UIImageView? {
        if (view.isKind(of: UIImageView.classForCoder())  && view.bounds.size.height <= 1.0) {
            return view as? UIImageView
        }
        for subView in view.subviews {
            let imageView = findNavLineImageViewOn(view: subView)
            if imageView != nil {
                return imageView
            }
        }
        return nil
    }
}
